package com.liuhengjia.auth;

import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyun.oss.common.auth.InvalidCredentialsException;
import com.aliyun.oss.common.utils.StringUtils;

/**
 * 自己可以自定义环境变量名
 */
public class MyEnvironmentVariableCredentialsProvider implements CredentialsProvider {
    public void setCredentials(Credentials creds) {
    }

    public Credentials getCredentials() {
        String accessKeyId = StringUtils.trim(System.getenv("ALY_OSS_AK_ID"));
        String secretAccessKey = StringUtils.trim(System.getenv("ALY_OSS_AK_SECRET"));
        String sessionToken = StringUtils.trim(System.getenv("OSS_SESSION_TOKEN"));
        if (accessKeyId != null && !accessKeyId.equals("")) {
            if (secretAccessKey != null && !secretAccessKey.equals("")) {
                return new DefaultCredentials(accessKeyId, secretAccessKey, sessionToken);
            } else {
                throw new InvalidCredentialsException("Secret access key should not be null or empty.");
            }
        } else {
            throw new InvalidCredentialsException("Access key id should not be null or empty.");
        }
    }
}